/*
********************************************************************************
* Copyright (C) 2022, xiang.D <dx_65535@163.com>.
* All right reserved.
*
* File Name   : originator.cc
* Author      :
* Version     : V1.0
* Description :
* Journal     : 2022-03-04 version v1.0
* Brief       : Blog: https://blog.csdn.net/qq_38750572?spm=1001.2014.3001.5343
* Others      :
                Compile command: make
********************************************************************************
*/

#include <time.h>
#include <string.h>
#include "originator.h"

using namespace std;

#define ORI_LOGD(fmt, args...) printf("%d Originator D: " fmt, __LINE__, ##args)
#define ORI_LOGE(fmt, args...) printf("%d Originator E: " fmt, __LINE__, ##args)
#define ORI_LOG(fmt, args...) printf(fmt, ##args)

COriginator::COriginator()
{
    memset(&mAttrValue, 0, sizeof(SAttrValue));
}

COriginator::~COriginator()
{

}

static void GetTime(char *pTimeBuf, int len)  // E.g. 2022-03-04 21:22:40
{
    int length = len;
    time_t timeValue;
    struct tm *info;

    if (NULL == pTimeBuf) {
        ORI_LOGE("pTimeBuf is NULL!\n");
        return;
    }

    time (&timeValue);
    info = localtime(&timeValue);
    strftime(pTimeBuf, length, "%Y-%m-%d %H:%M:%S", info);
}

CMemento* COriginator::Save()
{
    // 保存备份时刻时间
    GetTime(mAttrValue.date, sizeof(mAttrValue.date));
    CMemento *pMemento = new CMemento((void *)&mAttrValue, sizeof(SAttrValue));

    return pMemento;
}

void COriginator::Restore(CMemento *pMemento)
{
    int ret = 0;
    SAttrValue tmp;

    if (NULL == pMemento) {
        ORI_LOGE("pMemento is NULL!\n");
        return;
    }

    ret = pMemento->GetInfo((void *)&tmp, sizeof(SAttrValue));
    if (ret >= 0) {
        memset(&mAttrValue, 0, sizeof(SAttrValue));
        memcpy(&mAttrValue, &tmp, sizeof(SAttrValue));
        //ORI_LOGD("%d %f %s \n", mAttrValue.level, mAttrValue.blood, mAttrValue.date);
    } else {
        ORI_LOGE("Get attribute failed!\n");
    }
}

void COriginator::SetAttribute(SAttrValue *pAttr)
{
    if (NULL != pAttr) {
        memcpy(&mAttrValue, pAttr, sizeof(SAttrValue));
    } else {
        ORI_LOGE("pAttr is NULL!\n");
    }
}

void COriginator::ShowInfo()
{
    ORI_LOG("Level: %d\n"
            "Blood: %.0f%%\n",
            mAttrValue.level, mAttrValue.blood);

    if (strlen(mAttrValue.date) != 0) {
        ORI_LOG("Backup time: %s\n", mAttrValue.date);
    }
}